package http_proxy_middleware

import (
	"net/http/httputil"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"github.com/youkelike/gateway/core/middleware"
	"github.com/youkelike/gateway/dao"
	"github.com/youkelike/gateway/reverse_proxy"
)

var proxy_pool_map sync.Map

func getProxyPool(serviceDetail *dao.ServiceDetail) *sync.Pool {
	if val, ok := proxy_pool_map.Load(serviceDetail.Info.ServiceName); ok {
		return val.(*sync.Pool)
	}

	pool := &sync.Pool{
		New: func() any {
			return getReverseProxy(nil, serviceDetail)
		},
	}
	proxy_pool_map.Store(serviceDetail.Info.ServiceName, pool)

	return pool
}
func getReverseProxy(c *gin.Context, serviceDetail *dao.ServiceDetail) *httputil.ReverseProxy {
	lb, err := dao.LoadBalancerHandler.GetLoadBalancer(serviceDetail)
	if err != nil {
		return nil
	}
	// 连接池
	trans, err := dao.TransportorHandler.GetTrans(serviceDetail)
	if err != nil {
		return nil
	}

	return reverse_proxy.NewLoadBalanceReverseProxy(c, lb, trans)
}

// 匹配接入方式 基于请求信息
func HTTPReverseProxyMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serverInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serverInterface.(*dao.ServiceDetail)

		lb, err := dao.LoadBalancerHandler.GetLoadBalancer(serviceDetail)
		if err != nil {
			middleware.ResponseError(c, 2002, err)
			c.Abort()
			return
		}
		// 连接池
		trans, err := dao.TransportorHandler.GetTrans(serviceDetail)
		if err != nil {
			middleware.ResponseError(c, 2003, err)
			c.Abort()
			return
		}

		proxy := reverse_proxy.NewLoadBalanceReverseProxy(c, lb, trans)
		proxy.ServeHTTP(c.Writer, c.Request)
		c.Abort()

		// proxy, ok := dao.Pool[serviceDetail.Info.ServiceName]
		// if !ok {
		// 	middleware.ResponseError(c, 2003, fmt.Errorf("get reverse pool fail"))
		// 	return
		// }
		// proxy.ServeHTTP(c.Writer, c.Request)

		// c.Abort()
	}
}
